/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.investigateevidence.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.punish.common.electricsent.dto.DocumentSentAddressInfoRequest;
import com.icinfo.cloud.provider.punish.common.electricsent.vo.CaseDocumentSendinfoConfirmVo;
import com.icinfo.cloud.provider.punish.execute.service.IExecutePartyInfoService;
import com.icinfo.cloud.provider.punish.execute.vo.ExecutePartyInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CasePartiesLegalInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CasePartiesPersonInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CasePartiesRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CasePartiesLegalInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CasePartiesPersonInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CasePartiesRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseHolderVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentAuthedEntrustMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentSendinfoConfirmMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentAuthedEntrust;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentSendinfoConfirm;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.service.ICaseDocumentSendinfoConfirmService;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述: 送达方式和地址确认书 case_document_sendinfo_confirm 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月18日
 */
@Service
public class CaseDocumentSendinfoConfirmServiceImpl extends MyBatisServiceSupport implements ICaseDocumentSendinfoConfirmService {


    @Resource
    private CaseDocumentSendinfoConfirmMapper caseDocumentSendinfoConfirmMapper;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private CasePartiesPersonInfoMapper casePartiesPersonInfoMapper;
    @Resource
    private CasePartiesLegalInfoMapper casePartiesLegalnfoMapper;
    @Resource
    private IExecutePartyInfoService executePartyInfoService;
    @Resource
    private CaseDocumentAuthedEntrustMapper caseDocumentAuthedEntrustMapper;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;

    /**
     * 描述：根据案件信息查询文书送达地址确认书信息
     *
     * @param request {@link DocumentSentAddressInfoRequest}
     * @return {@link CaseDocumentSendinfoConfirmVo}
     * @author xiangyuyu
     * @date 2022-02-28 16:02
     */
    @Override
    public CaseDocumentSendinfoConfirmVo getCaseDocumentSendInfoConfirmInfo(DocumentSentAddressInfoRequest request) {
        String caseId = request.getCaseId();
        String partyId = request.getPartyId();
        if (ObjectUtils.isEmpty(caseId)) {
            throw new BusinessException("未指定案件id");
        }
        Example queryExample = new Example(CaseDocumentSendinfoConfirm.class);
        Example.Criteria criteria = queryExample.createCriteria();
        Example queryExampleAuthed = new Example(CaseDocumentAuthedEntrust.class);
        Example.Criteria criteriaAuthed = queryExampleAuthed.createCriteria();
        criteria.andEqualTo("caseId", caseId);
        criteriaAuthed.andEqualTo("caseId", caseId);
        criteriaAuthed.andEqualTo("status", Constant.INTEGER_1);
        if (!ObjectUtils.isEmpty(partyId)) {
            criteria.andEqualTo("partyId", partyId);
            criteriaAuthed.andLike("partyId", "%" + partyId + "%");
        } else {
            //校验必传性
            CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
            String casePartiesReasonType = caseMainInfo.getCasePartiesReasonType();
            if (ObjectUtils.isEmpty(partyId)) {
                if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(casePartiesReasonType)) {
                    throw new BusinessException("多当事人时送达流程指定当事人id");
                }
            }
        }
        List<CaseDocumentSendinfoConfirm> sendInfoConfirmList
                = caseDocumentSendinfoConfirmMapper.selectByExample(queryExample);
        List<CaseDocumentAuthedEntrust> caseDocumentAuthedEntrusts = caseDocumentAuthedEntrustMapper.selectByExample(queryExampleAuthed);
        CaseDocumentSendinfoConfirmVo vo = new CaseDocumentSendinfoConfirmVo();
        // 获取当事人和委托人信息
        List<CaseHolderVo> caseHolderVos = new ArrayList<>();
        Example query = new Example(CasePartiesRecord.class);
        Example.Criteria criteria1 = query.createCriteria();
        criteria1.andEqualTo("caseId", caseId).andEqualTo("status", "1");
        if (!ObjectUtils.isEmpty(partyId)) {
            criteria1.andEqualTo("partyId", partyId);
        }
        List<CasePartiesRecord> casePartiesRecords = casePartiesRecordMapper.selectByExample(query);
        if (!ObjectUtils.isEmpty(casePartiesRecords) && casePartiesRecords.size() > 0) {
            CasePartiesRecord casePartiesRecord = casePartiesRecords.get(Constant.INTEGER_0);
            CaseHolderVo caseHolderVo = new CaseHolderVo();
            caseHolderVo.setTypeName("当事人");
            caseHolderVo.setName(casePartiesRecord.getPartyName());
            caseHolderVo.setCertificateNo(casePartiesRecord.getPartyIdentityCode());
            if (PartyTypeEnum.PERSON.getCode().equals(casePartiesRecord.getPartyType())) {
                CasePartiesPersonInfo personInfo = casePartiesPersonInfoMapper.selectByPrimaryKey(casePartiesRecord.getPartyId());
                if (!ObjectUtils.isEmpty(personInfo)) {
                    caseHolderVo.setPhoneNum(personInfo.getMobile());
                }
            } else if (PartyTypeEnum.LEGAL.getCode().equals(casePartiesRecord.getPartyType())) {
                CasePartiesLegalInfo legalInfo = casePartiesLegalnfoMapper.selectByPrimaryKey(casePartiesRecord.getPartyId());
                if (!ObjectUtils.isEmpty(legalInfo)) {
                    caseHolderVo.setPhoneNum(legalInfo.getPhone());
                }
            }
            caseHolderVos.add(caseHolderVo);
        }
        if (!ObjectUtils.isEmpty(caseDocumentAuthedEntrusts) && caseDocumentAuthedEntrusts.size() > 0) {
            CaseDocumentAuthedEntrust caseDocumentAuthedEntrust = caseDocumentAuthedEntrusts.get(Constant.INTEGER_0);
            String[] splitName = caseDocumentAuthedEntrust.getAuthedName().split("、");
            String[] splitCertNo = caseDocumentAuthedEntrust.getAuthedCertNo().split("、");
            String[] authedMobile = caseDocumentAuthedEntrust.getAuthedMobile().split("、");
            for (int i = 0; i < splitName.length; i++) {
                CaseHolderVo caseHolderVo = new CaseHolderVo();
                caseHolderVo.setTypeName("委托人");
                caseHolderVo.setName(splitName[i]);
                caseHolderVo.setCertificateNo(splitCertNo[i]);
                caseHolderVo.setPhoneNum(authedMobile[i]);
                caseHolderVos.add(caseHolderVo);
            }
        }
        vo.setCaseHolderList(caseHolderVos);
        vo.setHasSentAddressConfirmInfo(YesOrNoEnum.YES.getCode());
        vo.setIsNeedConfirmBeforeSend(YesOrNoEnum.NO.getCode());
        if (ObjectUtils.isEmpty(sendInfoConfirmList) || sendInfoConfirmList.size() == 0) {
            //未匹配到相关送达地址确认书信息
            vo.setHasSentAddressConfirmInfo(YesOrNoEnum.NO.getCode());
        } else {
            //fixme:目前只取一条（是否需要加状态，后期优化可考虑）
            CaseDocumentSendinfoConfirm record = sendInfoConfirmList.get(Constant.INTEGER_0);
            if (!ObjectUtils.isEmpty(record)) {
                BeanUtils.copyProperties(record, vo);
            }
            Integer status = record.getStatus();
            if (!Constant.INTEGER_1.equals(status)) {
                vo.setHasSentAddressConfirmInfo(YesOrNoEnum.NO.getCode());
                vo.setIsNeedConfirmBeforeSend(YesOrNoEnum.YES.getCode());
            }
            String documentCatalogCode = record.getDocumentCatalogCode();
            // 通过案件id和当事人id和目录编码查询生成的送达地址确认书编码
            Example documentExample = new Example(CaseDocumentRecord.class);
            Example.Criteria criteria2 = documentExample.createCriteria();
            criteria2.andEqualTo("caseId", caseId)
                    .andEqualTo("documentCatalogCode", documentCatalogCode)
                    .andEqualTo("documentRecordStatus",Constant.STRING_1)
                    .andEqualTo("documentSignstampedStatus","SIGN_2");
            if (!StringUtils.isEmpty(partyId)){
                criteria2.andEqualTo("partyId",partyId);
            }
            List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(documentExample);
            if (!ObjectUtils.isEmpty(caseDocumentRecords) && caseDocumentRecords.size() > 0) {
                CaseDocumentRecord caseDocumentRecord = caseDocumentRecords.get(0);
                vo.setSendDocumentId(caseDocumentRecord.getId());
                vo.setShowWithdraw(Constant.STRING_1);
            }

        }
        vo.setIsNeedConfirmBeforeSendName(YesOrNoEnum.getValueByCode(vo.getIsNeedConfirmBeforeSend()));
        vo.setHasSentAddressConfirmInfoName(YesOrNoEnum.getValueByCode(vo.getHasSentAddressConfirmInfo()));
        String documentId = request.getDocumentId();
        if (!StringUtils.isEmpty(documentId)){
            CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(documentId);
            if (!ObjectUtils.isEmpty(caseDocumentRecord)){
                vo.setZlbService(caseDocumentRecord.getZlbService());
            }
        }
        return vo;
    }

    @Override
    public CaseDocumentSendinfoConfirmVo getDocumentSendInfoConfirmInfoByIdentityCode(String partyIdentityType, String partyIdentityCode) {
        Example queryExample = new Example(CaseDocumentSendinfoConfirm.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("partyIdentityCode", partyIdentityCode);
        if (ObjectUtil.isNotEmpty(partyIdentityType)) {
            criteria.andEqualTo("partyIdentityType", partyIdentityType);
        }
        List<CaseDocumentSendinfoConfirm> caseDocumentSendinfoConfirms = caseDocumentSendinfoConfirmMapper.selectByExample(queryExample);
        if (ObjectUtil.isNotEmpty(caseDocumentSendinfoConfirms) && caseDocumentSendinfoConfirms.size() > 0) {
            CaseDocumentSendinfoConfirmVo caseDocumentSendinfoConfirmVo = new CaseDocumentSendinfoConfirmVo();
            BeanUtils.copyProperties(caseDocumentSendinfoConfirms.get(0), caseDocumentSendinfoConfirmVo);
            return caseDocumentSendinfoConfirmVo;
        }
        return null;
    }

    @Override
    public List<CaseDocumentSendinfoConfirmVo> getCaseDocumentSendInfoConfirmInfoList(String caseId) {
        Example queryExample = new Example(CaseDocumentSendinfoConfirm.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("caseId", caseId);
        List<CaseDocumentSendinfoConfirm> caseDocumentSendinfoConfirms = caseDocumentSendinfoConfirmMapper.selectByExample(queryExample);
        List<CaseDocumentSendinfoConfirmVo> voList = new ArrayList<>();
        for (CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm : caseDocumentSendinfoConfirms) {
            CaseDocumentSendinfoConfirmVo confirmVo = new CaseDocumentSendinfoConfirmVo();
            BeanUtils.copyProperties(caseDocumentSendinfoConfirm, confirmVo);
            voList.add(confirmVo);
        }
        return voList;
    }

    @Override
    public CaseDocumentSendinfoConfirmVo getExecuteDocumentSendInfoConfirmInfo(DocumentSentAddressInfoRequest request) {
        String caseId = request.getCaseId();
        String partyId = request.getPartyId();
        if (ObjectUtils.isEmpty(caseId)) {
            throw new BusinessException("未指定案件id");
        }
        Example queryExample = new Example(CaseDocumentSendinfoConfirm.class);
        Example.Criteria criteria = queryExample.createCriteria();
        criteria.andEqualTo("caseId", caseId);
        if (!ObjectUtils.isEmpty(partyId)) {
            criteria.andEqualTo("partyId", partyId);
        } else {
            List<ExecutePartyInfoVo> executePartyInfo = executePartyInfoService.getExecutePartyInfo(caseId);
            if (executePartyInfo.size() > 1) {
                //增加送达当事人id处理
                if (ObjectUtils.isEmpty(partyId)) {
                    throw new BusinessException("多当事人时送达流程指定当事人id");
                }
            }
        }
        List<CaseDocumentSendinfoConfirm> sendInfoConfirmList
                = caseDocumentSendinfoConfirmMapper.selectByExample(queryExample);
        CaseDocumentSendinfoConfirmVo vo = new CaseDocumentSendinfoConfirmVo();
        vo.setHasSentAddressConfirmInfo(YesOrNoEnum.YES.getCode());
        vo.setIsNeedConfirmBeforeSend(YesOrNoEnum.NO.getCode());
        if (ObjectUtils.isEmpty(sendInfoConfirmList) || sendInfoConfirmList.size() == 0) {
            //未匹配到相关送达地址确认书信息
            vo.setHasSentAddressConfirmInfo(YesOrNoEnum.NO.getCode());
        } else {
            //fixme:目前只取一条（是否需要加状态，后期优化可考虑）
            CaseDocumentSendinfoConfirm record = sendInfoConfirmList.get(Constant.INTEGER_0);
            if (!ObjectUtils.isEmpty(record)) {
                BeanUtils.copyProperties(record, vo);
            }
            Integer status = record.getStatus();
            if (!Constant.INTEGER_1.equals(status)) {
                vo.setHasSentAddressConfirmInfo(YesOrNoEnum.NO.getCode());
                vo.setIsNeedConfirmBeforeSend(YesOrNoEnum.YES.getCode());
            }
        }

        vo.setIsNeedConfirmBeforeSendName(YesOrNoEnum.getValueByCode(vo.getIsNeedConfirmBeforeSend()));
        vo.setHasSentAddressConfirmInfoName(YesOrNoEnum.getValueByCode(vo.getHasSentAddressConfirmInfo()));
        return vo;
    }
}
